<template>
    <jb-page class="extract-page">
        <div class="flex-col">
            <div class="upload-section">
                <jb-upload :max="1" v-model="formData.url" :multiple="false"
                           accept=".pdf, .doc, .docx, .xls, .xlsx, .txt, .md"
                           save-path="sysnotice/{date(yyMMdd)}/{random(6)}/{ori}">
                    <div class="flex item-center">
                        <n-button type="primary" ghost>
                            <template #icon>
                                <jb-icon :local="true" icon="material-symbols:upload"></jb-icon>
                            </template>
                            上传文件
                        </n-button>
                    </div>
                </jb-upload>

                <n-button type="primary" @click="handleSubmit" :loading="loading" class="extract-btn">
                    <template #icon>
                        <jb-icon :local="true" icon="material-symbols:description-outline"/>
                    </template>
                    文档提取
                </n-button>
            </div>

            <!-- Results Section -->
            <div v-if="content" class="results-section">
                <n-card title="提取结果" class="results-card">
                    <template #header-extra>
                        <div style="display: flex; align-items: center; justify-content: end;width: 100%;">
                            <!--              <span class="result-count">共 {{ extractResults.length }} 条内容</span>-->
                            <n-button text style="margin-left: 8px" type="primary" @click="copyContent" size="small">
                                <template #icon>
                                    <jb-icon :local="true" icon="material-symbols:content-copy-outline"/>
                                </template>
                                复制全部
                            </n-button>
                        </div>
                    </template>

                    <div class="results-list">
                        <n-scrollbar style="height: 100%;">
                            <div class="content-item" style="height: 100%">
                                <div class="content-header">

                                </div>
                                <div class="content-body">
                                    <p class="content-text" style="max-width: 100%" v-html="md.render(content)"></p>
                                </div>
                            </div>
                        </n-scrollbar>
                    </div>
                </n-card>
            </div>
        </div>
    </jb-page>
</template>

<script setup>
import {
    ref
} from "vue";
import {
    JBoltApi
} from "@/service/request/index.js";
import {
    useMessage
} from 'naive-ui';
import markdownit from "markdown-it";

const message = useMessage();
const loading = ref(false);
const content = ref('');
const md = markdownit({
    html: true,
    breaks: true,
    linkify: true,
    typographer: true
});


const formData = ref({
    url: ''
})

function copyContent() {
    // navigator.clipboard.writeText(content.value).then(() => {
    //   message.success('复制成功');
    // }).catch(() => {
    //   message.error('复制失败');
    // });
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(content.value)
            .then(() => {
                console.log('内容已复制到剪贴板');
            })
            .catch((err) => {
                console.error('复制失败:', err);
            });
    } else {
        console.error('当前浏览器不支持 Clipboard API');
        // 降级方案：使用旧的 execCommand 方法
        fallbackCopyText(content.value);
    }
}

function fallbackCopyText(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        document.execCommand('copy');
        console.log('内容已复制到剪贴板（降级方案）');
    } catch (err) {
        console.error('复制失败（降级方案）:', err);
    }
    document.body.removeChild(textArea);
}

function copyAllContent() {
    const allContent = content.value.join('\n\n');
    navigator.clipboard.writeText(allContent).then(() => {
        message.success('全部内容已复制');
    }).catch(() => {
        message.error('复制失败');
    });
}

function handleSubmit() {
    if (!formData.value.url) {
        message.warning('请先上传文件');
        return;
    }
    loading.value = true;
    JBoltApi.tryGet(`/demo/docParseDemo`, {
        url: formData.value.url
    }).then((res) => {
        content.value = res.data;
        message.success('文档提取成功');
    }).catch((error) => {
        console.error(error);
    }).finally(() => {
        loading.value = false;
    });
}
</script>

<style scoped>
.extract-page {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.extract-page :deep(.n-card) {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.extract-page :deep(.n-card-header) {
    flex-shrink: 0;
}

.extract-page :deep(.n-card__content) {
    flex: 1;
    overflow: hidden;
    padding: 0 16px 16px;
}

.flex-col {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.upload-section {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-shrink: 0;
}

.extract-btn {
    height: 32px;
}

.results-section {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
}

.results-card {
    height: 100%;
}

.result-count {
    color: #606266;
    font-size: 14px;
}

.results-list {
    height: 100%;
}

.results-list :deep(.n-scrollbar) {
    height: 100%;
}

.results-list :deep(.n-scrollbar-container) {
    height: 100%;
}

.content-item {
    padding: 16px;
    background: #f9f9f9;
    border-radius: 6px;
    margin-bottom: 12px;
}

.content-item:last-child {
    margin-bottom: 0;
}

.content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.content-body {
    background: #fff;
    padding: 12px;
    border-radius: 4px;
    border: 1px solid #eee;
}

.content-text {
    margin: 0;
    line-height: 1.6;
    white-space: pre-wrap;
    word-break: break-word;
    font-size: 14px;
}

.content-text img {
    max-width: 100% !important;
}
</style>